<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer v-bind="$attrs" :showFooter="true" :okAuth="'shop:sales:shopSalesPackage:edit'"
    @register="registerDrawer" @ok="handleSubmit" width="60%">
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #shopSalesPackagesList>
        <BasicTable @register="registerShopSalesPackagesTable" @row-click="handleShopSalesPackagesRowClick" @edit-change="rowChange"/>
        <!-- <a-button class="mt-2" @click="handleShopSalesPackagesAdd" v-auth="'shop:sales:shopSalesPackage:edit'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsShopSalesShopSalesPackageForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { ShopSalesPackage, shopSalesPackageSavePacks, shopSalesPackageForm } from '/@/api/shop/sales/shopSalesPackage';
  import {  shopSalesPackagesForm,ShopSalesPackages } from '/@/api/shop/sales/shopSalesPackages';


  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('shop.sales.shopSalesPackage');
  const { showMessage } = useMessage();
  const record = ref < ShopSalesPackage > ({} as ShopSalesPackage);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增物料') : t('编辑物料'),
  }));

  const inputFormSchemas: FormSchema[] = [

    {
      label: t(''),
      field: 'shopSalesPackagesList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'shopSalesPackagesList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerShopSalesPackagesTable, shopSalesPackagesTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleShopSalesPackagesDelete.bind(this, record),
          },
          auth: 'shop:sales:shopSalesPackage:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    // bordered: true,
    // size: 'small',
    // inset: true,
    // canResize: true,
  });

  async function setShopSalesPackagesTableData() {
    shopSalesPackagesTable.setColumns([
      {
        title: t('物料编码'),
        dataIndex: 'invCode',
        width: 130,
        align: 'left',
      },
      {
        title: t('物料名称'),
        dataIndex: 'basInv.cinvname',
        width: 130,
        align: 'left',
      },
      {
        title: t('规格型号'),
        dataIndex: 'basInv.cinvstd',
        width: 100,
        align: 'left',
      },
      {
        title: t('单位'),
        dataIndex: 'basInv.unitName',
        width: 70,
        align: 'left',
      },
      {
        title: t('是否赠品'),
        dataIndex: 'bgift',
        width: 80,
        align: 'center',
        dictType: 'sys_yes_no',
        editable: true,
        edit: true,
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'sys_yes_no',
          // allowClear: true,
        },
        editRule: true,
      },
      {
        title: t('件数'),
        dataIndex: 'iqty',
        width: 80,
        align: 'center',
        editable: true,
        edit: true,
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 8,
        },
        editRule: true,
      },
      {
        title: t('单价'),
        dataIndex: 'iprice',
        width: 80,
        align: 'center',
        editable: true,
        edit: true,
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 8,
        },
        editRule: true,
      },
      {
        title: t('金额'),
        dataIndex: 'isum',
        width: 80,
        align: 'center',
      }
    ]);
    shopSalesPackagesTable.setTableData(record.value.list || []);
  }

  function handleShopSalesPackagesRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleShopSalesPackagesAdd() {
    shopSalesPackagesTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleShopSalesPackagesDelete(record: Recordable) {
    shopSalesPackagesTable.deleteTableDataRecord(record);
  }

  async function rowChange({ column, value, record }) {
    if (column.dataIndex == 'iqty') {
      record.iqty = value;
      if(record.iprice){
        record.isum = (record.iqty * record.iprice).toFixed(2);
      }
      

    }
    if (column.dataIndex == 'iprice') {
      record.iprice = value.toFixed(4);
      if(record.iqty){
        record.isum = (record.iqty * record.iprice).toFixed(2);
      }
    }
    if (column.dataIndex == 'bgift') {
      record.bgift = value;
      if (record.bgift == 1){
        record.iprice = '0';
        record.isum = '0';
      }
      if (record.bgift == 0){
        if(record.iqty && record.iprice){
          record.isum = (record.iqty * record.iprice).toFixed(2);
        }
      }
    }
  }

  async function getShopSalesPackagesList() {
    let shopSalesPackagesListValid = true;
    let shopSalesPackagesList: Recordable[] = [];
    for (const record of shopSalesPackagesTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        shopSalesPackagesListValid = false;
      }
      shopSalesPackagesList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of shopSalesPackagesTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      shopSalesPackagesList.push({
        ...record,
        status: '1',
      });
    }
    if (!shopSalesPackagesListValid) {
      throw { errorFields: [{ name: ['shopSalesPackagesList'] }] };
    }
    return shopSalesPackagesList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    console.log(data);
    let res = {}
    if(data.isNewRecord){
      console.log(data,'data====');
      res = await shopSalesPackagesForm({selInvs:data.selInvs});
    }else{
      res = await shopSalesPackagesForm({selIds:data.selIds});
    }
    // const res = await shopSalesPackagesForm(data);
    // record.value = (res.shopSalesPackages || {}) as ShopSalesPackages;
    record.value = data
    record.value.__t = new Date().getTime();
    record.value.list = res.shopSalesPackagesList
    setFieldsValue(record.value);
    setShopSalesPackagesTableData();
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        // isNewRecord: record.value.isNewRecord,
        id: record.value.id,
        wlType: record.value.wlType,
      };
      data.wlType = record.value.wlType
      data.id = record.value.id
      if(record.value.wlType == '0'){
        data.wlList = await getShopSalesPackagesList();
      }
      if(record.value.wlType == '1'){
        data.mainList = await getShopSalesPackagesList();
      }
      if(record.value.wlType == '2'){
        data.fpList = await getShopSalesPackagesList();
      }
      if(record.value.wlType == '3'){
        data.czpList = await getShopSalesPackagesList();
      }

      // console.log('submit', params, data, record);
      const res = await shopSalesPackageSavePacks(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data.wlType);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<style lang="less" scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }

  /* .jeesite-editable-cell__action {
    display: none;
  } */

  :deep(.edit-cell-align-center) {
    width: 100% !important;
  }
</style>
